import React, { useState, useEffect } from 'react';
import { StyleSheet, View, TouchableOpacity, ScrollView, Modal, Platform, Alert } from 'react-native';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { FontAwesome } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import DateTimePicker from '@react-native-community/datetimepicker';

interface PeriodRecord {
  id: string;
  start_date: Date;
  end_date: Date | null;
  duration?: number;
}

// API 请求函数
const API_BASE_URL = 'http://116.205.137.46'; // 更新为实际的API地址r
const USER_ID = 'hrw'; // 替换为实际的用户ID

const fetchPeriodRecords = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/periods?user_id=${USER_ID}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '获取记录失败');
    }
    
    const data = await response.json();
    if (!data.data) {
      return [];
    }
    
    return data.data.map((record: any) => ({
      ...record,
      start_date: new Date(record.start_date),
      end_date: record.end_date ? new Date(record.end_date) : null
    }));
  } catch (error) {
    console.error('获取记录失败:', error);
    throw error;
  }
};

const createPeriodRecord = async (startDate: Date) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/periods`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_id: USER_ID,
        start_date: startDate.toISOString().split('T')[0]
      })
    });
    if (!response.ok) throw new Error('创建记录失败');
    const data = await response.json();
    return {
      ...data.data,
      start_date: new Date(data.data.start_date),
      end_date: data.data.end_date ? new Date(data.data.end_date) : null
    };
  } catch (error) {
    console.error('创建记录失败:', error);
    throw error;
  }
};

const updatePeriodRecord = async (id: string, endDate: Date) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/periods/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        end_date: endDate.toISOString().split('T')[0]
      })
    });
    if (!response.ok) throw new Error('更新记录失败');
    const data = await response.json();
    return {
      ...data.data,
      start_date: new Date(data.data.start_date),
      end_date: data.data.end_date ? new Date(data.data.end_date) : null
    };
  } catch (error) {
    console.error('更新记录失败:', error);
    throw error;
  }
};

const deletePeriodRecord = async (id: string) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/periods/${id}`, {
      method: 'DELETE'
    });
    if (!response.ok) throw new Error('删除记录失败');
    return await response.json();
  } catch (error) {
    console.error('删除记录失败:', error);
    throw error;
  }
};

export default function PeriodTrackerScreen() {
  const [records, setRecords] = useState<PeriodRecord[]>([]);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [isStartDate, setIsStartDate] = useState(true);
  const [activeRecord, setActiveRecord] = useState<PeriodRecord | null>(null);
  const [nextPeriodDate, setNextPeriodDate] = useState<Date | null>(null);
  const [editingRecord, setEditingRecord] = useState<PeriodRecord | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [tempDate, setTempDate] = useState(new Date());
  const [isLoading, setIsLoading] = useState(false);
  const averageDuration = 7; // 平均经期持续天数

  // 加载记录
  useEffect(() => {
    loadRecords();
  }, []);

  const loadRecords = async () => {
    setIsLoading(true);
    try {
      const data = await fetchPeriodRecords();
      setRecords(data);
    } catch (error) {
      Alert.alert('错误', '加载记录失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 计算距离下次经期的天数
  useEffect(() => {
    if (records.length > 0) {
      const lastRecord = records[records.length - 1];
      if (lastRecord.end_date) {
        const averageCycle = 28; // 默认周期为28天
        const nextDate = new Date(lastRecord.end_date);
        nextDate.setDate(nextDate.getDate() + averageCycle);
        setNextPeriodDate(nextDate);
      }
    }
  }, [records]);

  // 删除记录
  const handleDelete = async (id: string) => {
    try {
      await deletePeriodRecord(id);
      setRecords(prev => prev.filter(record => record.id !== id));
      if (activeRecord?.id === id) {
        setActiveRecord(null);
      }
    } catch (error) {
      Alert.alert('错误', '删除记录失败，请重试');
    }
  };

  // 开始编辑记录
  const handleEdit = (record: PeriodRecord) => {
    setEditingRecord(record);
    setIsEditing(true);
    setSelectedDate(record.start_date);
    setIsStartDate(true);
    setShowDatePicker(true);
  };

  // 处理日期变化
  const handleDateChange = (event: any, date?: Date) => {
    if (Platform.OS === 'android') {
      setShowDatePicker(false);
      if (date) {
        handleDateConfirm(date);
      }
    } else {
      if (date) {
        setTempDate(date);
      }
    }
  };

  // 处理日期确认
  const handleDateConfirm = async (date: Date) => {
    try {
      if (isEditing && editingRecord) {
        if (isStartDate) {
          setEditingRecord(prev => prev ? {...prev, start_date: date} : null);
          if (editingRecord.end_date) {
            setIsStartDate(false);
            setSelectedDate(editingRecord.end_date);
            setTempDate(editingRecord.end_date);
            setShowDatePicker(true);
          } else {
            const updatedRecord = await updatePeriodRecord(editingRecord.id, date);
            setRecords(prev => prev.map(record => 
              record.id === editingRecord.id ? updatedRecord : record
            ));
            setIsEditing(false);
            setEditingRecord(null);
          }
        } else {
          const updatedRecord = await updatePeriodRecord(editingRecord.id, date);
          setRecords(prev => prev.map(record => 
            record.id === editingRecord.id ? updatedRecord : record
          ));
          setIsEditing(false);
          setEditingRecord(null);
        }
      } else {
        if (isStartDate) {
          const newRecord = await createPeriodRecord(date);
          setRecords(prev => [...prev, newRecord]);
          setActiveRecord(newRecord);
        } else if (activeRecord) {
          const updatedRecord = await updatePeriodRecord(activeRecord.id, date);
          setRecords(prev => prev.map(record => 
            record.id === activeRecord.id ? updatedRecord : record
          ));
          setActiveRecord(null);
        }
      }
    } catch (error) {
      Alert.alert('错误', '操作失败，请重试');
    }
    setShowDatePicker(false);
  };

  const formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}年${month}月${day}日`;
  };

  const getDaysUntilNext = () => {
    if (!nextPeriodDate) return null;
    const today = new Date();
    const diffTime = nextPeriodDate.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  // 获取月份显示
  const getMonthDisplay = (date: Date) => {
    const month = date.getMonth() + 1;
    return `${month}月`;
  };

  // 获取预计结束日期
  const getEstimatedEndDate = (startDate: Date) => {
    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + averageDuration);
    return endDate;
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <ThemedText style={styles.headerTitle}>经期记录</ThemedText>
      </View>

      <View style={styles.nextPeriodCard}>
        <LinearGradient
          colors={['#FFB6C1', '#FFC0CB']}
          style={styles.gradientBackground}
        >
          <ThemedText style={styles.nextPeriodTitle}>
            {activeRecord ? '本次经期' : '下次经期'}
          </ThemedText>
          {activeRecord ? (
            <>
              <ThemedText style={styles.nextPeriodDate}>
                预计 {formatDate(getEstimatedEndDate(activeRecord.start_date))} 结束
              </ThemedText>
              <ThemedText style={styles.countdown}>
                还有 {Math.ceil((getEstimatedEndDate(activeRecord.start_date).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} 天
              </ThemedText>
            </>
          ) : nextPeriodDate ? (
            <>
              <ThemedText style={styles.nextPeriodDate}>
                预计 {formatDate(nextPeriodDate)}
              </ThemedText>
              <ThemedText style={styles.countdown}>
                还有 {getDaysUntilNext()} 天
              </ThemedText>
            </>
          ) : (
            <ThemedText style={styles.noDataText}>
              请记录本次经期以预测下次日期
            </ThemedText>
          )}
        </LinearGradient>
      </View>

      <ScrollView style={styles.recordsList}>
        {records.map((record) => (
          <View key={record.id} style={styles.recordItem}>
            <View style={styles.monthBadge}>
              <ThemedText style={styles.monthText}>
                {getMonthDisplay(record.start_date)}
              </ThemedText>
            </View>
            <View style={styles.recordContent}>
              <View style={styles.recordDates}>
                <ThemedText style={styles.dateText}>
                  开始：{formatDate(record.start_date)}
                </ThemedText>
                <ThemedText style={styles.dateText}>
                  {record.end_date 
                    ? `结束：${formatDate(record.end_date)}` 
                    : '尚未结束'}
                </ThemedText>
                {record.duration && (
                  <ThemedText style={styles.durationText}>
                    持续：{record.duration}天
                  </ThemedText>
                )}
              </View>
              <View style={styles.recordActions}>
                <TouchableOpacity 
                  style={styles.actionButton}
                  onPress={() => handleEdit(record)}
                >
                  <FontAwesome name="edit" size={20} color="#FF69B4" />
                </TouchableOpacity>
                <TouchableOpacity 
                  style={styles.actionButton}
                  onPress={() => handleDelete(record.id)}
                >
                  <FontAwesome name="trash" size={20} color="#FF69B4" />
                </TouchableOpacity>
              </View>
            </View>
          </View>
        ))}
      </ScrollView>

      <View style={styles.footer}>
        <TouchableOpacity
          style={styles.addButton}
          onPress={() => {
            setIsStartDate(true);
            setShowDatePicker(true);
          }}
        >
          <LinearGradient
            colors={['#FF69B4', '#FFB6C1']}
            style={styles.gradientButton}
          >
            <FontAwesome name="plus" size={20} color="#fff" />
            <ThemedText style={styles.buttonText}>记录经期</ThemedText>
          </LinearGradient>
        </TouchableOpacity>

        {activeRecord && !activeRecord.end_date && (
          <TouchableOpacity
            style={styles.endButton}
            onPress={() => {
              setIsStartDate(false);
              setShowDatePicker(true);
            }}
          >
            <LinearGradient
              colors={['#FF69B4', '#FFB6C1']}
              style={styles.gradientButton}
            >
              <FontAwesome name="check" size={20} color="#fff" />
              <ThemedText style={styles.buttonText}>结束记录</ThemedText>
            </LinearGradient>
          </TouchableOpacity>
        )}
      </View>

      {showDatePicker && (Platform.OS === 'android' ? (
        <DateTimePicker
          value={selectedDate}
          mode="date"
          display="default"
          onChange={handleDateChange}
        />
      ) : (
        <Modal
          transparent={true}
          visible={showDatePicker}
          animationType="slide"
        >
          <View style={styles.modalContainer}>
            <View style={styles.modalContent}>
              <View style={styles.modalHeader}>
                <TouchableOpacity
                  style={styles.modalHeaderButton}
                  onPress={() => setShowDatePicker(false)}
                >
                  <ThemedText style={styles.modalButtonText}>取消</ThemedText>
                </TouchableOpacity>
                <ThemedText style={styles.modalTitle}>
                  {isStartDate ? '选择开始日期' : '选择结束日期'}
                </ThemedText>
                <TouchableOpacity
                  style={styles.modalHeaderButton}
                  onPress={() => handleDateConfirm(tempDate)}
                >
                  <ThemedText style={[styles.modalButtonText, styles.confirmText]}>确定</ThemedText>
                </TouchableOpacity>
              </View>
              <DateTimePicker
                value={tempDate}
                mode="date"
                display="spinner"
                onChange={handleDateChange}
                locale="zh-CN"
              />
            </View>
          </View>
        </Modal>
      ))}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    padding: 16,
    paddingTop: Platform.OS === 'android' ? 40 : 60,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#FF69B4',
  },
  nextPeriodCard: {
    margin: 16,
    borderRadius: 16,
    overflow: 'hidden',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  gradientBackground: {
    padding: 20,
    alignItems: 'center',
  },
  nextPeriodTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 8,
  },
  nextPeriodDate: {
    fontSize: 18,
    color: '#fff',
    marginBottom: 4,
  },
  countdown: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
  },
  noDataText: {
    fontSize: 16,
    color: '#fff',
    textAlign: 'center',
  },
  recordsList: {
    flex: 1,
    padding: 16,
  },
  recordItem: {
    backgroundColor: '#FFF0F5',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    marginTop: 10,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
  },
  recordContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  recordDates: {
    gap: 4,
  },
  dateText: {
    fontSize: 16,
    color: '#FF69B4',
  },
  durationText: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
  },
  recordActions: {
    flexDirection: 'row',
    gap: 16,
  },
  footer: {
    padding: 16,
    flexDirection: 'row',
    justifyContent: 'space-around',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  addButton: {
    flex: 1,
    marginHorizontal: 8,
  },
  endButton: {
    flex: 1,
    marginHorizontal: 8,
  },
  gradientButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 12,
    borderRadius: 25,
    gap: 8,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: '#fff',
    padding: 16,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  modalHeaderButton: {
    padding: 8,
  },
  modalTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  modalButtonText: {
    fontSize: 16,
    color: '#666',
  },
  confirmText: {
    color: '#FF69B4',
    fontWeight: 'bold',
  },
  actionButton: {
    padding: 8,
  },
  monthBadge: {
    position: 'absolute',
    top: -10,
    left: 16,
    backgroundColor: '#FF69B4',
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 12,
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 2,
  },
  monthText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 'bold',
  },
}); 